package com.example.baiduapi.Controller.SSEControle;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
public class TestSSE {
    private final Map<String,SseEmitter> pool = new HashMap();
    @PostMapping("/publisher/{id}")
    public void publisher(@PathVariable("id")String ID,
                          @RequestParam("content")String content){
        SseEmitter sseEmitter = pool.get(ID);
        if(Objects.isNull(sseEmitter)){
            return;
        }
        try {
            sseEmitter.send(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/subscribe/{id}")
    public SseEmitter subscribe(@PathVariable("id")String id) {
        SseEmitter sseEmitter = pool.get(id);
        if(Objects.isNull(sseEmitter)){
            sseEmitter = new SseEmitter(60*1000L); // （单位毫秒） 默认存活30s,0L为永久，这里设置一分钟，
            System.out.println(pool);
            sseEmitter.onCompletion(() -> pool.remove(id));
            sseEmitter.onTimeout(() -> pool.remove(id));

            pool.put(id,sseEmitter);
            System.out.println(pool);
        }
        return sseEmitter;
    }
}
